package com.marvels.common.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.marvels.common.data.DataRow;
import com.marvels.common.dto.MarvelsResultDTO;
import com.marvels.common.exception.MarvelsErrorCode;
import com.marvels.common.utils.ConfigProperties;
import com.marvels.common.utils.HttpUtils;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ShaUtils;
import com.marvels.common.utils.StringUtils;

public class SecurityInterceptor implements HandlerInterceptor {

	private ConfigProperties configProps;
	
	public SecurityInterceptor(ConfigProperties configProps){
		this.configProps = configProps;
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception exception)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handle) throws Exception {
		if("0".equals(configProps.getSignSwitch())){
			MarvelsLogUtil.getInstance().info("验签关闭！");
			return true;
		}
		
		String param = "";
		String type = request.getMethod();
		if(type.equals("POST")){
			param= HttpUtils.getBodyString(request);
		}else{
			param = HttpUtils.getGETParam(request);
			
		}
		JSONObject paramJson = JSON.parseObject(param);
		
		String time = (String)paramJson.get("time");
		String sign = (String)paramJson.get("sign");
		
		if(StringUtils.isEmpty(time)||StringUtils.isEmpty(sign)){
			returnErrorMessage(response,"验签失败:必要验签参数为空");
			return false;
		}
		Long timeL = Long.valueOf(time);
		if((timeL-System.currentTimeMillis())/1000>1*60){
			returnErrorMessage(response,"连接已超时");
			return false;
		}
		if(!sign.equals(ShaUtils.Encrypt(time+configProps.getSalt(), "UTF-8"))){
			returnErrorMessage(response,"签名不匹配");
			return false;
		}
		return true;
	}
	
	
	private void returnErrorMessage(HttpServletResponse response,String message) throws IOException{
		MarvelsResultDTO result = MarvelsResultDTO.getFailResult(MarvelsErrorCode.ERROR.getValue(), message);
		response.setContentType("application/json");
		PrintWriter writer = response.getWriter();
		writer.print(JSON.toJSONString(result));
		writer.flush();
	}
	
	/**
	 * @description 打印参数
	 * @param data
	 */
	private void outData(DataRow data,HttpServletResponse response) throws Exception{
		response.setContentType("application/json; charset=utf-8");  
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(JSONObject.toJSONString(data));
		response.getWriter().flush();
	}

}

